Skip to main content

Binary Search

The original case/problem could be found on leedcode

case 744 (classical case)

var nextGreatestLetter = function(letters, target) {
let low=0
let high=letters.length;
while(low<=high){
let mid=Math.floor(low+(high-low)/2) // import math form, the code of binary search!!!!
if(letters[mid]>target){
high=mid-1
}
else{
low=mid+1
}
}
return low>=letters.length?letters[0]:letters[low]
};
class Solution {

/**
* @param String[] $letters
* @param String $target
* @return String
*/
function nextGreatestLetter($letters, $target) {
$left = 0;
$right = count($letters);

while ($left<=$right) {
$mid = floor($left+($right-$left)/2);
if ($letters[$mid]>$target) $right = $mid-1;
else $left = $mid+1;
}

if ($left>=count($letters)) return $letters[0];
else return $letters[$left];
}
}